//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    items:[
      {value:'1',name:'连续工作'},
      {value:'0',name:'间歇工作'},
    ],
    disable:true,
    checked:true,
    deviceName: "Atomizer 913",
    isConnected: false,
    isFailed: true,
    isFinded: false,
    AtomizerIsPower:false,
    LEDIsPower:false,
    worktime:4,
    pausetime:300,
    mode:0,
  },
  CreatedLink() {
    let that = this;
    wx.openBluetoothAdapter({
      success: function(res) {
        if (!that.data.isConnected) {
          that.startBluetoothDevicesDiscovery();
          wx.showLoading({
            title: '搜索中',
          })
        }
      },
      fail: function(res) {
        wx.showToast({
          title: '请先开启蓝牙',
          icon: 'none',
          duration: 1000
        })
      }
    });
  },
  startBluetoothDevicesDiscovery: function() {
    var that = this;
    wx.startBluetoothDevicesDiscovery({
      success: function(res) {
        console.log("discovery", res);
        if (res.errCode == 0) {
          that.getConnect();
        }
      },
    });
  },
  getConnect: function() {
    var that = this;
    var timer = setInterval(function() {
        wx.getBluetoothDevices({
          success: function(res) {
            console.log("devices", res);
            for (var i = 0; i < res.devices.length; i++) {
              if (res.devices[i].name == that.data.deviceName) {
                wx.hideLoading();
                wx.showLoading({
                  title: '连接中',
                })
                that.setData({
                  isFinded: true
                });
                clearInterval(timer);
                that.setData({
                  deviceId: res.devices[i].deviceId
                });
                console.log('设备号', that.data.deviceId);
                console.log("开始尝试建立连接");
                wx.createBLEConnection({
                  deviceId: that.data.deviceId,
                  timeout: 10000,
                  success: function(res) {
                    console.log(res);
                    if (res.errCode == 0) {
                      console.log('连接成功')
                      that.setData({
                        isConnected: true
                      });
                      wx.stopBluetoothDevicesDiscovery();
                    } else {
                      wx.showModal({
                        title: '提示',
                        content: '不能正常对蓝牙设备进行连接',
                        showCancel: false
                      })
                    }
                  },
                  fail: (res) => {
                    wx.hideLoading();
                    if (res.errCode == 10012) {
                      wx.showModal({
                        title: '提示',
                        content: '连接超时',
                        showCancel: false
                      })
                    }
                    console.warn("fail", res);
                  },
                  complete: () => {
                    wx.hideLoading();
                  }
                })
                break;
              }
            }
          }
        });
      },
      3000);
    setTimeout(function() {
      if (!that.data.isFinded && !that.data.isConnected) {
        clearInterval(timer);
        that.setData({
          isFailed: false
        });
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '搜索蓝牙超时',
          showCancel: false
        })
      }
    }, 12000);
  },
  
  fillcmdbuff:function(command) {
    var buf = new ArrayBuffer(7);
    var bufView = new Uint8Array(buf);
    bufView[0] = 0x4C
    bufView[1] = command
    switch(command)
    {
    case 0:
      bufView[2] = this.data.mode
      bufView[4] = this.data.worktime & 0xff
      bufView[3] = this.data.worktime >> 8 & 0xff
      bufView[6] = this.data.pausetime & 0xff
      bufView[5] = this.data.pausetime >> 8 & 0xff
      break;
    case 1:
      if (this.data.AtomizerIsPower)
      {
        bufView[2] = 0
      }
      else
      {
        bufView[2] = 1
      }
      this.data.AtomizerIsPower = !this.data.AtomizerIsPower
      break;
    case 2:
      bufView[2] = 1
      bufView[3] = 80
      bufView[4] = 80
      bufView[5] = 80
      break;
    case 3:
      if (this.data.LEDIsPower)
      {
        bufView[2] = 0
      }
      else
      {
        bufView[2] = 1
      }
      this.data.LEDIsPower = !this.data.LEDIsPower
     break;
    }
    return buf
  },
  onWorkTime(e) {
    this.setData({
      worktime: e.detail.value
    })
  },
  onPauseTime(e){
    this.setData({
      pausetime:e.detail.value
    })
  },
  radioChange:function(e)
  {
    this.setData({
      mode:e.detail.value
    })
    console.log ('value',"=>"+e.detail.value)
  },

  SendData2Device(command)
  {
    let that = this;
    if(that.data.isConnected && that.data.isFailed){
    wx.showLoading({
      title: '获取serviceId',
    })
    console.log("开始获取设备信息");
    wx.getBLEDeviceServices({
      deviceId: that.data.deviceId,
      success(getServicesRes) {
        console.log("getServicesRes", getServicesRes);
        let service = getServicesRes.services[1]
        let serviceId = service.uuid
        wx.showLoading({
          title: '获取characteristicId',
        })
        wx.getBLEDeviceCharacteristics({
          deviceId: that.data.deviceId,
          serviceId: serviceId,
          success(getCharactersRes) {
            console.log("getCharactersRes", getCharactersRes);
            wx.hideLoading();
            let characteristic = getCharactersRes.characteristics[0]
            let characteristicId = characteristic.uuid
            that.setData({
              serviceId: serviceId,
              characteristicId: characteristicId
            })
            console.log('成功获取uuId', that.data.serviceId, that.data.characteristicId);
            wx.writeBLECharacteristicValue({
              deviceId: that.data.deviceId,
              serviceId: that.data.serviceId,
              characteristicId: getCharactersRes.characteristics[0].uuid,
              value: that.fillcmdbuff(command),
              success: function(res) {
                console.log("设置成功");
                wx.showToast({
                  title: '设置成功',
                  icon: 'none'
                })
              },
              fail: function(res) {
                console.warn("设置失败", res)
              }
            })            
          /*  wx.notifyBLECharacteristicValueChange({
              state: true,
              deviceId: that.data.deviceId,
              serviceId: serviceId,
              characteristicId: getCharactersRes.characteristics[2].uuid,
              success() {
                console.log('开始监听特征值')
                wx.onBLECharacteristicValueChange(function (onNotityChangeRes) {
                  console.log('监听到特征值更新', onNotityChangeRes);
                  let characteristicValue = that.ab2hex(onNotityChangeRes.value);
                  wx.showModal({
                    title: '监听到特征值更新',
                    content: `更新后的特征值(16进制格式):${characteristicValue}`,
                    showCancel: false
                  })
                })
              },
              fail: (res) => {
                console.warn("监听特征值失败");
              }
            })*/
          },
          fail: (res) => {
            console.warn("获取特征值信息失败", res);
          },
          complete: (res) => {
            console.log('获取服务信息完成',res);
            wx.hideLoading();
          }
        })
      },
      fail: (res) => {
        console.warn("获取服务信息失败", res);
      },
      complete: () => {
        wx.hideLoading();
      }
    })
    }else{
      wx.showToast({
        title: '请先连接蓝牙',
      })
    }
  },
  SaveSetting(){
    let that = this;
    if(that.data.isConnected && that.data.isFailed){
    wx.showLoading({
      title: '获取serviceId',
    })
    console.log("开始获取设备信息");
    wx.getBLEDeviceServices({
      deviceId: that.data.deviceId,
      success(getServicesRes) {
        console.log("getServicesRes", getServicesRes);
        let service = getServicesRes.services[1]
        let serviceId = service.uuid
        wx.showLoading({
          title: '获取characteristicId',
        })
        wx.getBLEDeviceCharacteristics({
          deviceId: that.data.deviceId,
          serviceId: serviceId,
          success(getCharactersRes) {
            console.log("getCharactersRes", getCharactersRes);
            wx.hideLoading();
            let characteristic = getCharactersRes.characteristics[0]
            let characteristicId = characteristic.uuid
            that.setData({
              serviceId: serviceId,
              characteristicId: characteristicId
            })
            console.log('成功获取uuId', that.data.serviceId, that.data.characteristicId);
            wx.writeBLECharacteristicValue({
              deviceId: that.data.deviceId,
              serviceId: that.data.serviceId,
              characteristicId: getCharactersRes.characteristics[0].uuid,
              value: that.fillcmdbuff(0),
              success: function(res) {
                console.log("设置成功");
                wx.showToast({
                  title: '设置成功',
                  icon: 'none'
                })
              },
              fail: function(res) {
                console.warn("设置失败", res)
              }
            })            
          /*  wx.notifyBLECharacteristicValueChange({
              state: true,
              deviceId: that.data.deviceId,
              serviceId: serviceId,
              characteristicId: getCharactersRes.characteristics[2].uuid,
              success() {
                console.log('开始监听特征值')
                wx.onBLECharacteristicValueChange(function (onNotityChangeRes) {
                  console.log('监听到特征值更新', onNotityChangeRes);
                  let characteristicValue = that.ab2hex(onNotityChangeRes.value);
                  wx.showModal({
                    title: '监听到特征值更新',
                    content: `更新后的特征值(16进制格式):${characteristicValue}`,
                    showCancel: false
                  })
                })
              },
              fail: (res) => {
                console.warn("监听特征值失败");
              }
            })*/
          },
          fail: (res) => {
            console.warn("获取特征值信息失败", res);
          },
          complete: (res) => {
            console.log('获取服务信息完成',res);
            wx.hideLoading();
          }
        })
      },
      fail: (res) => {
        console.warn("获取服务信息失败", res);
      },
      complete: () => {
        wx.hideLoading();
      }
    })
    }else{
      wx.showToast({
        title: '请先连接蓝牙',
      })
    }
  },

  Terminate_Link:function()
  {
    this.setData({
      isConnected:false,
      isFinded:false
    })
    wx.closeBLEConnection({
      deviceId: this.data.deviceId,
      success: function(res) {
        console.log("成功断开连接");
        wx.showToast({
          title: '成功断开连接',
        })
      },
    })
  },

   CloseLink(){
    this.setData({
      isConnected:false,
      isFinded:false
    })
    wx.closeBLEConnection({
      deviceId: this.data.deviceId,
      success: function(res) {
        console.log("成功断开连接");
        wx.showToast({
          title: '成功断开连接',
        })
      },
    })
  },

  AtomizerPower(){
    if(this.data.isConnected)
    {
      this.SendData2Device(1)
      this.setData({
//        AtomizerIsPower:!AtomizerIsPower
      })
      console.log("Atomizer power is on or off.");
    }
  },
  LEDPower(){
    if(this.data.isConnected)
    {
      this.SendData2Device(3)
      this.setData({
//        LEDIsPower:!LEDIsPower
      })
    }
  }


})